package com.baize.cpdepus.service.lmp;

import com.baize.cpdepus.common.RedisCache;
import com.baize.cpdepus.entity.Order;
import com.baize.cpdepus.entity.User;
import com.baize.cpdepus.mapper.OrderMapper;
import com.baize.cpdepus.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Time;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RedisCache redisCache;

    @Override
    public void add(Order order) {
        order.setTime(new Date());
        redisCache.setDbIndex(3);
        int uuid = UUID.randomUUID().toString().replaceAll("-", "").hashCode();
        uuid = uuid < 0 ? -uuid : uuid;//String.hashCode() 值会为空
        order.setID((long) uuid);
        redisCache.setCacheObject("order" + order.getID(),order,15, TimeUnit.MINUTES);
        // ToDo 没写好
    }

    @Override
    public Order orderIdOne(Long orderId) {
        redisCache.setDbIndex(3);
        Order orderByRedis = redisCache.getCacheObject("orderId" + orderId);
        if (Objects.nonNull(orderByRedis)) return orderByRedis;
        Order orderByMysql = orderMapper.select(orderId);
        redisCache.setCacheObject("orderId" + orderId, orderByMysql);
        return orderByMysql;
    }

    @Override
    public List<Order> sellerIdAll(Integer sellerId) {
        redisCache.setDbIndex(3);
        List<Order> ordersByRedis = redisCache.getCacheObject("sellerId" + sellerId);
        if (Objects.nonNull(ordersByRedis)) return ordersByRedis;
        List<Order> ordersByMysql = orderMapper.sellerIdSelect(sellerId);
        redisCache.setCacheObject("sellerId", ordersByMysql);
        return ordersByMysql;
    }

    @Override
    public List<Order> purchaserIdAll(Integer purchaserId) {
        redisCache.setDbIndex(3);
        List<Order> ordersByRedis = redisCache.getCacheObject("purchaserId" + purchaserId);
        if (Objects.nonNull(ordersByRedis)) return ordersByRedis;
        List<Order> ordersByMysql = orderMapper.purchaserIdSelect(purchaserId);
        redisCache.setCacheObject("purchaserId" + purchaserId, ordersByMysql);
        return ordersByMysql;
    }
}
